package com.example.hcd.adapt;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.datamanage.UserInfoData;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

public class AddressAdapt extends BaseAdapter implements Filterable{
	private Context context;
	private ArrayList<UserInfoData> userinfoList = new ArrayList<UserInfoData>();
	private LayoutInflater mInflate;
	
	 private PersonFilter filter;
	
    public AddressAdapt(Context activity) {
    	this.context = activity;
    	mInflate = LayoutInflater.from(context);
    }
 
    public void setList(ArrayList<UserInfoData> userinfoList)
    {
    	if (this.userinfoList != null) {
    		this.userinfoList.clear();
    		this.userinfoList.addAll(userinfoList);
        } else {
        	this.userinfoList = userinfoList;
        }
        notifyDataSetInvalidated();
    	
    }
    
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return userinfoList.size();
	}

	@Override
	public UserInfoData getItem(int arg0) {
		// TODO Auto-generated method stub
		return userinfoList.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate the views from XML
        View rowView = convertView;
        
        //if (rowView == null) {
            rowView = mInflate.inflate(R.layout.address_book_item, null);
        //}
            rowView.setBackgroundColor(context.getResources().getColor(R.color.light_white));
        UserInfoData userinfo = getItem(position);

        // Load the image and set it on the ImageView
        String name = userinfo.name;
        String mobiephone = userinfo.mobileNumber;
        
        TextView namestr = (TextView)rowView.findViewById(R.id.true_name); 
        
        TextView mobiephonestr = (TextView)rowView.findViewById(R.id.true_phone); 
        
        namestr.setText(name);
        
        mobiephonestr.setText(mobiephone);
        
        ImageView imageView = (ImageView)rowView.findViewById(R.id.people_pic);
        imageView.setImageResource(R.drawable.mrtx);
        
        new LoadHeadPic(userinfo, imageView).execute();
        
        return rowView;
    }
    
    private class LoadHeadPic extends AsyncTask<String, Integer, String> {

		private UserInfoData userdata;
		private ImageView view;
		public LoadHeadPic(UserInfoData data,ImageView view) {
			this.userdata = data;
			this.view = view;
		}
		@Override
		protected void onPreExecute() {

		}
		

		@Override
		protected String doInBackground(String... params) {
			
			if(userdata.headBitmap!=null)
			{
				
				return "head_have";
			}
			
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;

			try {
				
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("userId", userdata.id));

				response = LinkHelp.post(URLS.getOtherPhoto(), vs, false);
				if (response != null) {
					
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						InputStream in = response.getEntity().getContent();
						byte[] data = readStream(in);
						result = new String(data);
						if (result.contains("error")) {
							
							JSONObject jsonObject = new JSONObject(result);
							String msg = jsonObject.getString("msg");
							System.out.println(userdata.name+","+msg);
							
						} else {
							Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // 生成位图
							if (bitmap != null) {
					            view.setImageBitmap(toRoundBitmap(bitmap));
					            userdata.headBitmap = bitmap;
					            System.out.println("图片替换了");
					            
					        } else {
					        	//Bitmap bitmap = BitmapFactory.decodeResource(MenuActivity.mContext.getResources(), R.drawable.mrtx);
					        	view.setImageResource(R.drawable.mrtx);
					        	//imageView.setImageBitmap(toRoundBitmap(bitmap));
					            System.out.println("图片没替换");
					        }
						}
						

						return result;

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {

			if (TextUtils.isEmpty(result)) {
				
			} else {
				if(result.equals("head_have"))
				{
					view.setImageBitmap(toRoundBitmap(userdata.headBitmap));
				}

			}
		}
		
		public  byte[] readStream(InputStream in) throws Exception {
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.close();
			in.close();
			return outputStream.toByteArray();
		}

	}
    public Bitmap toRoundBitmap(Bitmap bitmap) {  
        int width = bitmap.getWidth();  
        int height = bitmap.getHeight();  
        float roundPx;  
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;  
        if (width <= height) {  
            roundPx = width / 2;  
            left = 0;  
            top = 0;  
            right = width;  
            bottom = width;  
            height = width;  
            dst_left = 0;  
            dst_top = 0;  
            dst_right = width;  
            dst_bottom = width;  
        } else {  
            roundPx = height / 2;  
            float clip = (width - height) / 2;  
            left = clip;  
            right = width - clip;  
            top = 0;  
            bottom = height;  
            width = height;  
            dst_left = 0;  
            dst_top = 0;  
            dst_right = height;  
            dst_bottom = height;  
        }  
  
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);  
        Canvas canvas = new Canvas(output);  
  
        final int color = 0xff424242;  
        final Paint paint = new Paint();  
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);  
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);  
        final RectF rectF = new RectF(dst);  
  
        paint.setAntiAlias(true);// 设置画笔无锯齿  
  
        canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas  
        paint.setColor(color);  
  
        // 以下有两种方法画圆,drawRounRect和drawCircle  
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形，第一个参数为图形显示区域，第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。  
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);  
  
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452  
        canvas.drawBitmap(bitmap, src, dst, paint); //以Mode.SRC_IN模式合并bitmap和已经draw了的Circle  
          
        return output;  
    }

	@Override
	public Filter getFilter() {
		// TODO Auto-generated method stub
		if (filter == null) {  
            filter = new PersonFilter(userinfoList); 
        }  
        return filter; 
	}
	
	private class PersonFilter extends Filter
	{
		private ArrayList<UserInfoData> userinfoLists = new ArrayList<UserInfoData>();
		public PersonFilter(ArrayList<UserInfoData> userinfoList) {
			this.userinfoLists = userinfoList;
			// TODO Auto-generated constructor stub
		}
		
		
		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults results = new FilterResults();  
            if (constraint == null || constraint.length() == 0) {  
                results.values = userinfoLists;  
                results.count = userinfoLists.size();  
            } else {  
                List<UserInfoData> mList = new ArrayList<UserInfoData>();  
                for (UserInfoData p: userinfoLists) {  
                    if (p.name.toUpperCase().startsWith(constraint.toString().toUpperCase())  
                        ) {  
                        mList.add(p);  
                    }  
                }  
                results.values = mList;
                results.count = mList.size();  
            }  
            return results;
		}

		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			// TODO Auto-generated method stub
			userinfoList = (ArrayList<UserInfoData>)results.values;  
            notifyDataSetChanged();
		}
		
	}

	

}
